Vue.component('yl-goods', {
    template: `<el-dialog id="ylGoods"  title="商品选择" :visible.sync="visibleDialog" width="80vw">
        <el-form :inline="true" :form="form">
            <el-form-item>
                <el-input v-model.trim="Article_Name" clearable placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select v-model.trim="selectSupplier" collapse-tags multiple style="width: 100%;" clearable placeholder="筛选供应商">
                    <el-option v-for="item in supplier" :key="item.Supplier_SerialNumber" :label="item.Supplier_Name" :value="item.Supplier_SerialNumber"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-cascader v-model="selectclassify" filterable collapse-tags clearable placeholder="分类汇总"
                    :props="defaultProps" :options="classify" style="width: 300px"></el-cascader>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="onSerach">查询</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData.slice((form.page-1)*form.limit,form.page*form.limit)"  :row-key="row=>row.Supplier_Article_SerialNumber" stripe border height="50vh" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" :reserve-selection="true" width="50"></el-table-column>
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="Article_Specifications_SerialNumber" show-overflow-tooltip label="供应商品内码"></el-table-column>
            <el-table-column align="center" prop="Supplier_Name" show-overflow-tooltip label="供应商名称"></el-table-column>
            <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
            <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip label="规格名称"></el-table-column>
            <el-table-column align="center" prop="Purchase_Unit_Price" show-overflow-tooltip label="采购价格"></el-table-column>
            <el-table-column align="center" prop="Unit_Price" show-overflow-tooltip label="吊牌价"></el-table-column>
            <el-table-column align="center" prop="Picture_URL" width="140" align="center" label="商品封面">
                <template v-slot="{row}">
                    <el-image fit="contain" :src="BASE_IMG + row.Picture_URL" style="width:100px;height: 100px;"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
                <template v-slot="{row,$index}">
                    <el-button size="small" :disabled="loading" type="danger" @click="handleRemove($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="form.page" :page-sizes="[10, 30 , 60 ,100, 200, 300, 400]" :page-size="form.limit"
            layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
        </el-pagination>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button type="primary" @click="submit()">确定</el-button>
        </span>
    </el-dialog>`,
    props: ['data', 'visible'],
    data() {
        return {
            visibleDialog: false,
            tableData: [],//详情
            form: {
                SQLSerialNumber: "A_business_supplier_article2",
                Condition: '',
                ExtensionCondition: '',
                page:1,
                limit:10,
            },
            total:0,
            activeName:"1",
            loading: false,
            supplier:[],//全部品牌
            classify:[],//全部类别
            screen:[{
                label:'相同商品取采购价格最低',
                value:'0'
            },{
                label:'相同商品取采购价格最高',
                value:'1'
            }],
            selectSupplier:[],//已选品牌
            selectclassify:[],//已选分类
            Article_Name:'',//商品名称
            defaultProps:{
                children: 'Children',
                label: 'Classify_Name',
                value: 'Classify_SerialNumber',
                multiple: true,
            },
            multipleSelection:[],
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val);
        },
    },
    methods: {
        onSerach(){
            let classify = []
            this.selectclassify.forEach(item => {
                classify = uniqueArr([...classify,...item]);
            })
            let sql = " and business_article_info.Article_Name LIKE '%"+this.Article_Name+"%'\r\n";
            //去重
            if(classify.length > 0){
                let str = "";
                classify.forEach((item,index)=>{
                    if (index==0) {
                        str =  "business_article_classify.Classify_SerialNumber = '"+ item +"' \r\n"
                    }else {
                        str = str + " or business_article_classify.Classify_SerialNumber = '"+ item +"' \r\n"
                    }
                })
                sql = sql + "and (" + str + ")\r\n"
            }
            if (this.selectSupplier.length > 0) {
                let str = "";
                this.selectSupplier.forEach((item,index)=>{
                    if (index==0) {
                        str =  "business_supplier_info.Supplier_SerialNumber = '"+ item +"' \r\n"
                    }else {
                        str = str + " or business_supplier_info.Supplier_SerialNumber = '"+ item +"' \r\n"
                    }
                })
                sql = sql + "and (" + str + ")\r\n"
            }
            this.form.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)))
            this.getList(this.form);
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleSelectionChange(val){
            this.multipleSelection = val;
        },
        handleRemove(index){
            this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
        },  
        getList(data) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submit(){
            if (this.multipleSelection.length > 0) {
                this.$emit('success',this.multipleSelection);
                this.$emit('update:visible', false)
            }else{
                this.$message({
                    message: '请先选择商品',
                    type: 'warning'
                })
            }
        },
        getData(){
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_supplier_info',
                    Condition:"Row_Status='0'",
                },
                success: function (res) {
                    that.supplier = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/getAllClassify`,
                type: 'GET',
                success: function (data) {
                    that.classify = data
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        }
    },
    mounted(){
        this.getData();
    },
})
new Vue({
    el: '#app',
    data() {
        const validateEnd_Date = (rule, value, callback) => {
            if (value && +new Date(value) < +new Date(this.form.Start_Date)) {
                callback(new Error('结束时间不能小于开始时间'));
            } else {
                callback();
            }
        }
        return {
            form: {
                Sales_Unit_Price_SerialNumber: '',
                Start_Date: '',//供应商名称
                End_Date: '',//所属地址
                Enterprise_Info_SerialNumber: '',
                Children: {
                    business_sales_unitprice_detail: [],
                    business_sales_unitprice_storescope: []
                },
                Store_SerialNumber: [],
            },
            page: {
                page: 1,
                limit: 10,
            },
            Store_SerialNumber:'',
            dialogVisible:false,
            rules: {
                Start_Date: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
                End_Date: [{ required: true, validator: validateEnd_Date, trigger: 'change' }],
                Store_SerialNumber: [{ required: true, message: '请选择适用店铺', trigger: 'change' }]
            },
            store: [],
            loading: false,
        }
    },
    watch: {
        'form.Store_SerialNumber': {
            handler(newVal) {
                this.form.Children.business_sales_unitprice_storescope = [];//初始化
                newVal.forEach(Store_SerialNumber => {
                    this.form.Children.business_sales_unitprice_storescope.push({
                        Sales_Unit_Price_StoreScope_SerialNumber: '',
                        Sales_Unit_Price_SerialNumber: '',
                        Store_SerialNumber,
                    })
                })
            },
            deep: true,
        }
    },
    mounted() {
        if (getCookie('role')) {
            let roleObj = JSON.parse(getCookie('role'));
            this.Store_SerialNumber = roleObj.other;
            this.form.Store_SerialNumber = [this.Store_SerialNumber]
        }
        this.getData();
    },
    methods: {
        getArticle(data){
            data.forEach(i=>{
                i.Sales_Unit_Price =  Number(i.Unit_Price);
            })
            this.form.Children.business_sales_unitprice_detail = data;
        },
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: "business_brand",
                    Condition: "Row_Status='0'"
                },
                success: function (data) {
                    that.brand = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: "business_store_info",
                    Condition: "Row_Status='0'"
                },
                success: function (data) {
                    that.store = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (that.form.Children.business_sales_unitprice_detail.length > 0) {
                        if (that.form.End_Date==null) {
                            that.form.End_Date = '';
                        }
                        that.loading = true
                        $.ajax({
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/generalBusiness/generalSave`,
                            type: 'POST',
                            data: {
                                Data: JSON.stringify({ Add: { business_sales_unitprice: [that.form] } })
                            },
                            success: function (res) {
                                if (res.Status === 'success') {
                                    that.$message.success("提交成功")
                                    window.history.go(-1)
                                } else {
                                    that.$message.error("提交失败，请稍后再试")
                                }
                            },
                            complete: function (XMLHttpRequest) {
                                that.loading = false
                                requestPretreatment(XMLHttpRequest);//config/config.js 响应预检
                            },
                            dataType: "json"
                        })
                    } else {
                        that.$message({
                            message: '没有选择适用商品',
                            type: 'warning'
                        })
                        return false;
                    }
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        handleSizeChange(val) {
            this.page.page = 1;
            this.page.limit = val;
        },
        handleCurrentChange(val) {
            this.page.page = val;
        },
        handleRemove(index) {//移除当前行
            this.$confirm('是否要删除此行?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.form.Children.business_sales_unitprice_detail = this.form.Children.business_sales_unitprice_detail.filter((i, id) =>  id != (this.page.page - 1) * this.page.limit + index)
            }).catch(() => { });
        },
    }
})